var _       = require('underscore');
var async   = require('async');
var db      = require('../models');
var cnv     = require('./conversation')

exports.drawer = function(req, res){
  res.render('drawer', { title: 'Welcome' });
};

exports.state = function(req, res){
  var state = {
    location : {
      marked : false
    }
  }

  var url = decodeURIComponent(req.query.url)

  // Check if location is marked
  db.Location.find({where: {user_id:req.user.id, url: url}}).success(function(location) {
    if (location)
    {
      state.location.marked = location.marked;
    }

    //cnv.top(req, res); // this does not work, because state info is missing from the response

    state.top_notes = {};

    // TODO: Remove this duplication, same code appears in the conversation.js
    db.Conversation.findAll({where: {user_id :req.user.id}, order: '`started` DESC', limit:3}).success(function(conversations) {
      async.map(conversations, function(item, callback) {
        db.Note.find({where: {user_id :req.user.id, conversation_id: item.id}, order: '`added` DESC', limit:1}).success(function(note) {
          state.top_notes[note.conversation_id] = note;
          callback(null, item)
        });
      }, function(err, results) {
        state.conversations = results;
        res.json(200, state);
      })

    });
  });

  // TODO: Check sequelize error handling
}

exports.act = function(req, res){
  var action = req.body.action;
  console.log(action);
  if (action.type == "an") { // add note action
    console.log("Add new note");
    db.Note
    .build({ author_id: req.user.id, text: action.data.text, added: new Date() })
    .save()
    .success(function(newNote) {
      console.log("New note added");
      res.send(200);
    }).error(function(error) {
      console.log("New note error", error);
      res.json(400, {message:'Location save failed'});
    })
  }
};

